package com.lyc.project.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.lyc.common.model.entity.Order;
import com.lyc.common.model.entity.User;
import com.lyc.project.common.BaseResponse;
import com.lyc.project.common.ErrorCode;
import com.lyc.project.common.ResultUtils;
import com.lyc.project.exception.BusinessException;
import com.lyc.project.exception.ThrowUtils;
import com.lyc.project.model.dto.order.*;
import com.lyc.project.model.vo.OrderVO;
import com.lyc.project.service.TOrderService;
import com.lyc.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 订单接口
 */
@RestController
@RequestMapping("/order")
@Slf4j
@CrossOrigin
public class OrderController {

    @Resource
    private TOrderService orderService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    /**
     * 创建订单
     *
     * @param orderAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<OrderVO> addOrder(@RequestBody OrderAddRequest orderAddRequest, HttpServletRequest request) {
        if (orderAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        OrderVO order = orderService.addOrder(orderAddRequest, request);
        return ResultUtils.success(order);
    }

    /**
     * 删除订单
     *
     * @param orderDeleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteOrder(@RequestBody OrderDeleteRequest orderDeleteRequest, HttpServletRequest request) {
        if (orderDeleteRequest == null || orderDeleteRequest.getOrderNumber() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        String orderNumber = orderDeleteRequest.getOrderNumber();
        // 判断是否存在
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getOrderSn, orderNumber);
        Order oldOrder = orderService.getOne(lqw);
        ThrowUtils.throwIf(oldOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldOrder.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = orderService.deleteOrder(orderDeleteRequest, request);
        return ResultUtils.success(b);
    }


    /**
     * 支付订单
     * @param orderPayRequest
     * @param request
     * @return
     */
    @PostMapping("/pay")
    public BaseResponse<Boolean> payOrder(@RequestBody OrderPayRequest orderPayRequest, HttpServletRequest request) {
        if(orderPayRequest == null || StrUtil.isBlank(orderPayRequest.getOrderNumber())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        String orderNumber = orderPayRequest.getOrderNumber();
        // 判断是否存在
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Order::getOrderSn, orderNumber);
        Order oldOrder = orderService.getOne(lqw);
        Integer status = oldOrder.getStatus();
        if (status != 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        ThrowUtils.throwIf(oldOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可操作
        if (!oldOrder.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = orderService.payOrder(orderPayRequest, request);
        return ResultUtils.success(b);
    }


    /**
     * 分页获取列表（封装类）
     *
     * @param orderQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<OrderVO>> listOrderVOByPage(@RequestBody OrderQueryRequest orderQueryRequest,
            HttpServletRequest request) {
        Page<OrderVO> orderVOPage = orderService.listPageOrder(orderQueryRequest, request);
        return ResultUtils.success(orderVOPage);
    }


    /**
     * 编辑订单购买数量（用户）
     *
     * @param orderEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editOrder(@RequestBody OrderEditRequest orderEditRequest, HttpServletRequest request) {
        if (orderEditRequest == null || orderEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Order order = new Order();
        BeanUtils.copyProperties(orderEditRequest, order);
        // 参数校验
        User loginUser = userService.getLoginUser(request);
        long id = orderEditRequest.getId();
        // 判断是否存在
        Order oldOrder = orderService.getById(id);
        ThrowUtils.throwIf(oldOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldOrder.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = orderService.updateById(order);
        return ResultUtils.success(result);
    }

}
